package com.ibangnuo.manage.controller.login;

import com.ibangnuo.framework.domain.User;
import com.ibangnuo.framework.model.response.CommonCode;
import com.ibangnuo.framework.model.response.ObjectResult;
import com.ibangnuo.framework.utils.ImgUtil;
import com.ibangnuo.framework.web.BaseController;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: wwy
 * @Date: 2019-12-27 12:08
 */
@Controller
@RequestMapping("")
public class Login extends BaseController {
    private static Logger LOGGER = LoggerFactory.getLogger(Login.class);
    /**
     * 登录
     */
    @PostMapping("/login")
    @ResponseBody
    public ObjectResult login(@RequestBody Map<String,String> map){
        Map<String,Object> map1 = new HashMap<>();
        HttpSession session = request.getSession();
        String verifyCode = String.valueOf(session.getAttribute("verifyCode"));
        if(!verifyCode.equalsIgnoreCase(map.get("verifyCode"))){
            map1.put("message","验证码错误");
            return new ObjectResult(CommonCode.FAIL,map1);
        }

        UsernamePasswordToken token = new UsernamePasswordToken(map.get("username"),map.get("password"));
        Subject subject = SecurityUtils.getSubject();

        SecurityUtils.getSubject().getSession().setTimeout(1800000);
        //SecurityUtils.getSubject().getSession().setTimeout(1*60*1000);
        try {
            subject.login(token);
            User user = (User) SecurityUtils.getSubject().getPrincipal();
            int type = user.getType();
            /*if(type == 4){
                type = 1;
            }
            if(type == 5){
                type = 2;
            }*/
            if(Integer.parseInt(map.get("type"))!= type){
                //登录失败
                this.logout();
                map1.put("message","账号密码错误");
                return new ObjectResult(CommonCode.FAIL,map1);
            }
        } catch (UnknownAccountException e) {
            //账户不存
            map1.put("message","账户不存在");
            return new ObjectResult(CommonCode.FAIL,map1);
        }catch (IncorrectCredentialsException e){
            //密码错误
            map1.put("message","密码错误");
            return new ObjectResult(CommonCode.FAIL,map1);
        }
        map1.put("message","登录成功");
        return new ObjectResult(CommonCode.SUCCESS,map1);
    }
    @GetMapping("/getCodeImg")
    public void getVerificationCodeImg(){
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");
        //生成随机字符串
        String verifyCode = ImgUtil.generateVerifyCode(4);
        LOGGER.info("验证码为：{}",verifyCode);
        //将字符串写入输出流 130宽 40高
        try {
            ImgUtil.outputImage(93, 31, response.getOutputStream(), verifyCode);
        } catch (IOException e) {
            LOGGER.error("验证码生成io错误{}",e.getMessage());
        }
        //存入Session
        HttpSession session = request.getSession(true);
        session.setAttribute("verifyCode",verifyCode);
    }

    @PostMapping("/logout")
    @ResponseBody
    public ObjectResult logout(){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        Map<String,Object> map = new HashMap<>();
        map.put("message","退出成功");
        return new ObjectResult(CommonCode.SUCCESS,map);
    }
}
